/**
 * 客户端类：随机生成字长为20的字符串，用socket发给服务器户端
 *
 * 2008-3-17
 * @author 李威
 *
 *
 */
package lsd.client;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import lsd.util.SocketUtil;

public class ClientService implements Client, Runnable {

    private String myName = null;

    public ClientService(String myName) {
        this.myName = myName;
    }

    public void run() {
        init();
    }

    /**
     * 随机生成字长为20的字符串
     * @return String 返回随机生成的字符串
     */
    public String getString() {
        int add;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 20; i++) {
            add = (int) (Math.random() * 25);
            char c = 'a';
            c = (char) (c + add);
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * 初始化客户端,用socket发字符串给服务器户端
     */
    public void init() {
        System.out.println("Client " + myName + " start~!");
        String sendString = getString();
        try {
            Socket conn;
            conn = new Socket("127.0.0.1", SocketUtil.port);
            //XXX 初始化客户端,用socket发字符串给服务器户端
            //			//写
            //			PrintWriter send = new PrintWriter(conn.getOutputStream());
            //			send.write(sendString);
            //			send.flush();
            OutputStream send = conn.getOutputStream();
            InputStream reader = conn.getInputStream();
            StringBuffer sb = new StringBuffer();
            while (true) {
                //写

                String temp = myName + " send " + sendString + " to server";
                System.out.println(temp);
                send.write(temp.getBytes());
                send.flush();

                //读

                int n = 1024;
                byte[] buffer = new byte[n];
                int sum = reader.read(buffer);
                if (sum != -1) {
                    sb.append(new String(buffer).substring(0, sum));
                    System.out.println(sb.toString());
                    sb.delete(0, sb.length());
                } else
                    break;
            }
            send.close();
            reader.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
